package cn.nawang.ebeim.server.util;

import cn.nawang.ebeim.server.constants.Config;
import cn.nawang.ebeim.server.queue.EbeimQueues;
import cn.nawang.ebeim.server.thread.TaskExecutor;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ThreadPoolUtil {

  /**
   * netty服务端线程
   */
  private static final int RECEIVE_CLIENT_CONNECT_SIZE = 1;

  /**
   * 扫描版本树上传文件夹线程
   */
  private static final int SCAN_VERSION_TREE_UPLOADFOLDER = 1;

  /**
   * 扫描文件上传文件夹线程
   */
  private static final int SCAN_FILE_UPLOADFOLDER = 1;


  /**
   * 从api获取版本树数据迁移任务线程
   */
  private static final int READ_VERSION_TREE_TODO = 1;

  /**
   * 从api获取数据迁移任务线程
   */
  private static final int READ_FILE_TODO = 1;

  /**
   * 处理版本树上传线程数
   */
  private static final int READ_VERSION_TREE_TO_HDFS = 5;

  /**
   * 处理文件上传线程数
   */
  private static final int READ_FILE_TO_HDFS = Config.THREAD_SIZE;

  /**
   * 处理版本树文件数据迁移线程数
   */
  private static final int HANDLE_VERSION_TREE_TODO = 5;

  /**
   * 处理文件数据迁移线程数
   */
  private static final int HANDLE_FILE_TODO = 5;

  /**
   * 处理API交互线程
   */
  private static final int UPDATE_TO_API_THREAD = 10;

  private static final int THREAD_POOL_SIZE =
      RECEIVE_CLIENT_CONNECT_SIZE + READ_VERSION_TREE_TO_HDFS
          + READ_FILE_TO_HDFS + SCAN_VERSION_TREE_UPLOADFOLDER + SCAN_FILE_UPLOADFOLDER
          + READ_VERSION_TREE_TODO + READ_FILE_TODO + HANDLE_VERSION_TREE_TODO + HANDLE_FILE_TODO + UPDATE_TO_API_THREAD;

  private static ExecutorService executorService = Executors.newFixedThreadPool(THREAD_POOL_SIZE);

  public static void startUploadVersionTreeToHdfsThread() {
    for (int i = 0; i < READ_VERSION_TREE_TO_HDFS; i++) {
      submitTask(new TaskExecutor(EbeimQueues.uploadVersionTreeQueue));
    }
  }

  public static void startUploadFileToHdfsThread() {
    for (int i = 0; i < READ_FILE_TO_HDFS; i++) {
      submitTask(new TaskExecutor(EbeimQueues.uploadFileQueue));
    }
  }

  public static void startUploadToApiServerThread() {
    for (int i = 0; i < UPDATE_TO_API_THREAD; i++) {
      submitTask(new TaskExecutor(EbeimQueues.updateToApiServerQueue));
    }
  }

  public static void startHandleVersionTreeTodoThread() {
    for (int i = 0; i < HANDLE_VERSION_TREE_TODO; i++) {
      submitTask(new TaskExecutor(EbeimQueues.handleVersionTreeTodoQueue));
    }
  }

  public static void startHandleFileTodoThread() {
    for (int i = 0; i < HANDLE_FILE_TODO; i++) {
      submitTask(new TaskExecutor(EbeimQueues.handleFileTodoQueue));
    }
  }

  public static void submitTask(Runnable task){
    executorService.submit(task);
  }

}
